import { defineStore } from 'pinia'
import { MessageProps, UpdatedStreamData, MessageStatus } from '../types'
import { db } from '../db'

export interface MessageStore {
    items: MessageProps[]
}

export const useMessageStore = defineStore('message', {
    state: (): MessageStore => {
        return {
            items: []
        }
    },
    actions: {
        async fetchMessagesByConversationId(conversationId: number) {
            const items = await db.messages.where({ conversationId }).toArray()
            this.items = items
        },
        async createMessage(createdData: Omit<MessageProps, 'id'>) {
            const newMessageId = await db.messages.add(createdData)
            this.items.push({
                id: newMessageId,
                ...createdData
            })
            return newMessageId
        },
        async updateMessage(streamData: UpdatedStreamData) {
            const { messageId, data } = streamData
            const curMessage = this.items.find(item => item.id === messageId)
            if (curMessage) {
                const updatedData = {
                    // content: curMessage.content + data.result,
                    status: (data.is_end ? 'finished' : 'streaming') as MessageStatus,
                    updatedAt: new Date().toISOString(),
                    ...(!data.is_end && { content: curMessage.content + data.result })
                }
                // 首先更新本地状态（避免多个流数据块几乎同时到达时，数据库更新可能在完成前被覆盖，导致只保留最后一个流数据块内容更新。）
                const index = this.items.findIndex(item => item.id === messageId)
                if ( index !== -1) {
                    this.items[index] = { ...this.items[index], ...updatedData }
                }
                
                // 更新数据库
                await db.messages.update(messageId, updatedData)
            }
        }
    },
    getters: {
        getLastQuestion: (state) => (conversationId: number) => {
            return state.items.findLast(item => item.conversationId === conversationId && item.type === 'question')
        }
    }
})